package com.ly.heart.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.ly.common.PageParam;
import com.ly.common.core.domain.AjaxResult;
import com.ly.common.core.domain.entity.SysDept;
import com.ly.common.exception.CustomException;
import com.ly.common.utils.DateUtils;
import com.ly.common.utils.SecurityUtils;
import com.ly.common.utils.StringUtils;
import com.ly.common.utils.erp.BatchNumberGenerator;
import com.ly.common.utils.erp.ConstUtil;
import com.ly.common.utils.erp.SnowflakeIdWorker;
import com.ly.heart.domain.*;
import com.ly.heart.domain.dto.ContractOrderMaterialDetailDto;
import com.ly.heart.domain.dto.ContractProcureOrderDto;
import com.ly.heart.domain.dto.StartProcessDto;
import com.ly.common.core.domain.ActCurrentTaskVo;
import com.ly.heart.domain.vo.ContractOrderMaterialDetailVo;
import com.ly.heart.domain.vo.ContractProcureOrderVo;
import com.ly.heart.mapper.ContractOrderMapper;
import com.ly.heart.mapper.ContractProcureMapper;
import com.ly.heart.mapper.MaterialDetailMapper;
import com.ly.heart.service.IActModelService;
import com.ly.heart.service.IActTaskCommentService;
import com.ly.heart.service.IContractProcureService;
import com.ly.heart.service.IFileInfoService;
import com.ly.heart.util.ChineseToPinyin;
import com.ly.heart.util.CurrentUserUtil;
import com.ly.system.service.ISysDeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;

/**
 * 采购合同;1:采购;2:行政;Service业务层处理
 * @author wutao
 * @date 2024-05-31
 */
@Service
@Slf4j
public class ContractProcureServiceImpl extends ServiceImpl<ContractProcureMapper, ContractProcureEntity> implements IContractProcureService {

    @Resource
    private ContractProcureMapper contractProcureEntityMapper;
    @Resource
    private ContractOrderMapper contractOrderMapper;
    @Resource
    private MaterialDetailMapper materialDetailMapper;
    @Resource
    private IFileInfoService iFileInfoService;
    @Resource
    private ISysDeptService deptService;
    @Resource
    private IActModelService iActModelService;
    @Resource
    private IActTaskCommentService iActTaskCommentService;

    /**
     * 查询采购合同;1:采购;2:行政;
     * @param id 采购合同;1:采购;2:行政;ID
     * @return 采购合同;1:采购;2:行政;
     */
    @Override
    public ContractProcureOrderVo selectContractProcureEntityById (String id) {
        //1.基本详情
        ContractProcureEntity contractProcureEntity = contractProcureEntityMapper.selectContractProcureEntityById ( id );
        contractProcureEntity.setIsCloseName ( contractProcureEntity.getIsClose () == 1 ? "正常" : "关闭" );
        contractProcureEntity.setIsCancelName ( contractProcureEntity.getIsCancel () == 1 ? "正常" : "作废" );
        //查询物料明细
        MaterialDetailEntity materialDetailEntity = new MaterialDetailEntity ();
        materialDetailEntity.setRelationId ( id );
        List<MaterialDetailEntity> materialDetailEntities = materialDetailMapper.selectOrderWarehouseDetailEntityList ( materialDetailEntity );
        ContractProcureOrderVo vo = new ContractProcureOrderVo ();
        vo.setContractProcureEntity ( contractProcureEntity );
        vo.setMaterialDetailEntities ( materialDetailEntities );
        return vo;
    }


    /**
     * 查询采购合同;1:采购;2:行政;列表
     * @param contractProcureEntity 采购合同;1:采购;2:行政;
     * @return 采购合同;1:采购;2:行政;
     */
    @Override
    public AjaxResult selectContractProcureEntityList (ContractProcureEntity contractProcureEntity) {
        contractProcureEntity.setIsUsed ( ConstUtil.IS_USED_YES );
        contractProcureEntity.setPage ( ( contractProcureEntity.getPage () - 1 ) * contractProcureEntity.getLimit () );
        List<ContractProcureEntity> contractProcureEntities = contractProcureEntityMapper.selectContractProcureEntityList ( contractProcureEntity );
        contractProcureEntities.forEach ( contract -> {
            //处理最后一个审批人
            ActTaskCommentEntity actTaskCommentEntity = iActTaskCommentService.queryLastComment ( contract.getInstanceId () );
            if ( actTaskCommentEntity != null ) {
                contract.setApprovedUser ( actTaskCommentEntity.getApprovedUser () );
                contract.setApprovedRemark ( actTaskCommentEntity.getRemark () );
            }
            //任务信息
            ActCurrentTaskVo currentTaskVo = iActModelService.getCurrentTaskByInstanceId ( contract.getInstanceId () );
            Optional.ofNullable ( currentTaskVo ).ifPresent ( currentTask -> {
                contract.setCurrentTask ( currentTask );
            } );
            contract.setIsCloseName ( contract.getIsClose () == 1 ? "正常" : "关闭" );
            contract.setIsCancelName ( contract.getIsCancel () == 1 ? "正常" : "作废" );
        } );
        PageParam page = new PageParam ();
        page.setTotal ( contractProcureEntityMapper.queryCount ( contractProcureEntity ) ).setRecords ( contractProcureEntities );
        return AjaxResult.success ( page );
    }

    /**
     * 新增采购合同、变更采购合同
     * 新增采购合同;1:采购;2:行政;
     * 新增采购合同时，要带入采购订单列表，以及采购物料列表
     * 根据是否有parentId判断是否是新增还是变更
     * 变更前置条件：新变更的数量只能小于等于未生成采购订单的数量
     * 1、采购合同如采购合同基本表
     * 2、采购订单入合同订单关联表
     * 3、采购物料入合同物料关联表
     * @param contractProcureOrderDto 采购合同;1:采购;2:行政;
     * @return 结果
     */
    @Override
    @Transactional (rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public AjaxResult draft (ContractProcureOrderDto contractProcureOrderDto) {
        //1、处理采购合同基本信息
        ContractProcureEntity contractProcureEntity = contractProcureOrderDto.getContractProcureEntity ();
        contractProcureEntity.setId ( SnowflakeIdWorker.getInstance ().nextStringId () );
        contractProcureEntity.setCreateBy ( SecurityUtils.getLoginUser ().getUser ().getUserId () );
        contractProcureEntity.setCreateTime ( DateUtils.getNowDate () );
        //解决合同编号规则
        if ( StringUtils.isNotBlank ( contractProcureEntity.getParentId () ) ) {
            //如果原合同关闭了，则不可变更了
            if ( contractProcureEntity.getIsClose () == ConstUtil.CONTRACT_IS_CLOSE_YES ) {
                return AjaxResult.error ( "【".concat ( contractProcureEntity.getContractName () ).concat ( "】已关闭，不能变更！" ) );
            }
            //说明走变更，根据父编号生成编号：老编号_001
            ContractProcureEntity parentContract = baseMapper.selectById ( contractProcureEntity.getParentId () );
            String contractNumber = parentContract.getContractNumber ();
            int count = this.count ( new QueryWrapper<ContractProcureEntity> ().eq ( "parent_id", contractProcureEntity.getParentId () ) );
            String countStr = String.format ( "%08d", count );
            contractProcureEntity.setContractNumber ( contractNumber.concat ( "_" ).concat ( countStr ) );
            contractProcureEntity.setIsChange ( ConstUtil.CONTRACT_IS_CHANGE_YES );
            //变更要检查数量，是否小于等于未生成采购订单的剩余数量，每个物料的数量不能超过已执行采购订单的物料的数量
            checkNumber ( contractProcureOrderDto.getMaterialDetailEntities () );
        } else {
            SysDept sysDept = deptService.getById ( SecurityUtils.getLoginUser ().getUser ().getDeptId () );
            String firstLetter = ChineseToPinyin.getFirstLetter ( sysDept.getDeptName () );
            String nowDateString = new SimpleDateFormat ( "yyyy-MM-dd" ).format ( new Date () );
            int count = this.count ( new QueryWrapper<ContractProcureEntity> () );
            String countStr = String.format ( "%08d", count );
            String contractNumber = firstLetter.concat ( "_" ).concat ( "采购合同" ).concat ( "_" ).concat ( nowDateString ).concat ( countStr );
            contractProcureEntity.setContractNumber ( contractNumber );
            contractProcureEntity.setIsChange ( ConstUtil.CONTRACT_IS_CHANGE_NO );
        }
        contractProcureEntity.setCreateTime ( DateUtils.getNowDate () );
        //2、处理合同附件
        List<FileEntity> fileEntities = contractProcureEntity.getFileEntities ();
        updateFile ( fileEntities, contractProcureEntity.getId () );
        //4、处理采购物料
        List<MaterialDetailEntity> materialDetailEntities = contractProcureOrderDto.getMaterialDetailEntities ();
        int updateMaterial = updateMaterial ( materialDetailEntities, contractProcureEntity.getId () );
        if ( updateMaterial == 0 ) {
            return AjaxResult.error ( "暂存采购合同与物料明细关联关系失败" );
        }
        contractProcureEntity.setState ( ConstUtil.STATE_IN_DRAFT );
        boolean save = this.save ( contractProcureEntity );
        if ( ! save ) {
            throw new CustomException ( "暂存采购合同失败！" );
        }
        return AjaxResult.success ( "暂存采购合同成功", contractProcureEntity.getId () );
    }


    @Override
    @Transactional (rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public AjaxResult submit (ContractProcureEntity contractProcureEntity) {
        //1、处理采购合同基本信息
        if ( StringUtils.isBlank ( contractProcureEntity.getId () ) ) {
            return AjaxResult.error ( "请先暂存单据！" );
        }
        //创建审批流
        StartProcessDto startDto = new StartProcessDto ().
                setBusinessId ( contractProcureEntity.getId () ).
                setBusinessType ( contractProcureEntity.getBusinessType () ).setModelId ( contractProcureEntity.getModelId () ).
                setBusinessName ( "采购合同_".concat ( contractProcureEntity.getId () ) );
        String instanceId = iActModelService.startProcess ( startDto );
        contractProcureEntity.setInstanceId ( instanceId );
        boolean update = this.update ( new LambdaUpdateWrapper<ContractProcureEntity> ().
                set ( ContractProcureEntity :: getInstanceId, instanceId ).
                set ( ContractProcureEntity :: getState, ConstUtil.STATE_IN_PROCESS ).
                eq ( ContractProcureEntity :: getId, contractProcureEntity.getId () ) );
        if ( ! update ) {
            throw new CustomException ( "新增采购合同失败！" );
        }
        return AjaxResult.success ( "新增采购合同成功" );
    }

    /**
     * 修改采购合同
     * 修改部分基本信息
     * @param contractProcureOrderDto 采购合同;1:采购;2:行政;
     * @return 结果
     */
    @Override
    @Transactional (rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public AjaxResult updateContractProcureEntity (ContractProcureOrderDto contractProcureOrderDto) {
        ContractProcureEntity contractProcureEntity = contractProcureOrderDto.getContractProcureEntity ();
        ContractProcureEntity sourceContract = this.getById ( contractProcureEntity );
        if ( sourceContract.getState ().equals ( ConstUtil.STATE_FINISH ) ) {
            return AjaxResult.error ( "审批完成的单据无法操作！" );
        }
        contractProcureEntity.setUpdateBy ( SecurityUtils.getLoginUser ().getUser ().getUserId () );
        contractProcureEntity.setUpdateTime ( DateUtils.getNowDate () );
        //2、处理合同附件
        List<FileEntity> fileEntities = contractProcureEntity.getFileEntities ();
        updateFile ( fileEntities, contractProcureEntity.getId () );
        //4、处理采购物料
        List<MaterialDetailEntity> materialDetailEntities = contractProcureOrderDto.getMaterialDetailEntities ();
        int updateMaterial = updateMaterial ( materialDetailEntities, contractProcureEntity.getId () );
        if ( updateMaterial == 0 ) {
            return AjaxResult.error ( "新增采购合同与物料明细关联关系失败" );
        }
        boolean b = this.updateById ( contractProcureEntity );
        if ( ! b ) {
            throw new CustomException ( "修改采购合同基本信息失败！" );
        }
        return AjaxResult.success ();
    }

    /**
     * 批量删除采购合同;1:采购;2:行政;
     * @param ids 需要删除的采购合同;1:采购;2:行政;ID
     * @return 结果
     */
    @Override
    @Transactional (rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public AjaxResult deleteContractProcureEntityByIds (String[] ids) {
        LambdaUpdateWrapper<ContractProcureEntity> contractUpdate = new LambdaUpdateWrapper<> ();
        contractUpdate.set ( ContractProcureEntity :: getIsUsed, ConstUtil.IS_USED_NO );
        contractUpdate.in ( ContractProcureEntity :: getId, ids );
        boolean update = this.update ( contractUpdate );
        if ( ! update ) {
            throw new CustomException ( "删除采购合同失败！" );
        }
        LambdaUpdateWrapper<MaterialDetailEntity> detailUpdate = new LambdaUpdateWrapper<> ();
        detailUpdate.set ( MaterialDetailEntity :: getIsUsed, ConstUtil.IS_USED_NO );
        detailUpdate.in ( MaterialDetailEntity :: getRelationId, ids );
        int updateDetail = materialDetailMapper.update ( null, detailUpdate );
        if ( updateDetail == 0 ) {
            throw new CustomException ( "删除采购合同失败！" );
        }
        return AjaxResult.success ( "删除采购合同成功" );
    }

    /**
     * 采购合同关闭、反关闭
     * @param id
     * @return
     */
    @Override
    public AjaxResult close (String id) {
        ContractProcureEntity procureEntity = this.getById ( id );
        if ( procureEntity == null ) {
            return AjaxResult.error ( "无此合同！" );
        }
        boolean update = this.update ( new LambdaUpdateWrapper<ContractProcureEntity> ().
                set ( ContractProcureEntity :: getIsClose, procureEntity.getIsClose () == 1 ? 2 : 1 ).
                set ( ContractProcureEntity :: getUpdateBy, SecurityUtils.getLoginUser ().getUser ().getUserId () ).
                set ( ContractProcureEntity :: getUpdateTime, DateUtils.getNowDate () ).
                eq ( ContractProcureEntity :: getId, id ) );
        if ( ! update ) {
            throw new CustomException ( procureEntity.getIsClose () == 1 ? "采购合同关闭失败！" : "采购合同反关闭失败！" );
        }
        return AjaxResult.success ( procureEntity.getIsClose () == 1 ? "采购合同关闭成功！" : "采购合同反关闭成功！" );
    }

    /**
     * 作废
     * @param id
     * @return
     */
    @Override
    public AjaxResult cancel (String id) {
        ContractProcureEntity procureEntity = this.getById ( id );
        if ( procureEntity == null ) {
            return AjaxResult.error ( "无此合同！" );
        }
        //作废要在单据没有审核完成之前才能做作废处理
        if ( ConstUtil.STATE_FINISH.equals ( procureEntity.getState () ) ) {
            return AjaxResult.error ( "采购合同【" + procureEntity.getContractNumber () + "】已审批完成，无法作废！" );
        }
        boolean update = this.update ( new LambdaUpdateWrapper<ContractProcureEntity> ().
                set ( ContractProcureEntity :: getIsCancel, 2 ).
                set ( ContractProcureEntity :: getUpdateBy, SecurityUtils.getLoginUser ().getUser ().getUserId () ).
                set ( ContractProcureEntity :: getUpdateTime, DateUtils.getNowDate () ).
                eq ( ContractProcureEntity :: getId, id ) );
        if ( ! update ) {
            throw new CustomException ( "采购合同作废失败！" );
        }
        return AjaxResult.success ( "采购合同作废成功！" );
    }


    /**
     * 根据采购合同对象List查询物料明细
     * 查询关联关系表，根据：
     * 1、relation_id合同Id
     * 2、type：采购合同明细=5
     * @return
     */
    @Override
    public AjaxResult queryMaterial (ContractOrderMaterialDetailDto contractOrderMaterialDetailDto) {
        contractOrderMaterialDetailDto.setPage ( ( contractOrderMaterialDetailDto.getPage () - 1 ) * contractOrderMaterialDetailDto.getLimit () );
        List<ContractOrderMaterialDetailVo> materialDetails = contractProcureEntityMapper.queryMaterial ( contractOrderMaterialDetailDto );
        Integer count = contractProcureEntityMapper.queryMaterialCount ( contractOrderMaterialDetailDto );
        PageParam p = new PageParam ();
        p.setRecords ( materialDetails ).setTotal ( count );
        return AjaxResult.success ( p );
    }

    /**
     * 修改勘测基础模块的附件，更新relationId为勘测记录Id
     * @param fileEntities
     * @param relationId
     */
    private void updateFile (List<FileEntity> fileEntities, String relationId) {
        if ( fileEntities != null && fileEntities.size () > 0 ) {
            fileEntities.forEach ( fileEntity -> {
                fileEntity.setRelationId ( relationId );
                fileEntity.setChangeTime ( DateUtils.getNowDate () );
            } );
            boolean b = iFileInfoService.updateBatchById ( fileEntities );
            if ( ! b ) {
                throw new RuntimeException ( "修改采购合同附件失败" );
            }
        }
    }

    /**
     * 处理采购合同与采购订单关联关系
     * 先删除原有关系，再新增现有关系
     * @param orderEntities
     * @param contractId
     * @return
     */
//    private int updateOrder (List<OrderEntity> orderEntities, String contractId) {
//        if ( orderEntities != null && orderEntities.size () > 0 ) {
//            ContractOrderEntity contractOrderEntity = new ContractOrderEntity ();
//            contractOrderEntity.setContractId ( contractId );
//            contractOrderEntity.setSourceContractType ( ConstUtil.CONTRACT_PROCURE_TYPE );
//            contractOrderMapper.delete ( new QueryWrapper<ContractOrderEntity> ().eq ( "contract_id", contractId ).eq ( "source_contract_type", ConstUtil.CONTRACT_PROCURE_TYPE ) );
//            //新增现有关系
//            orderEntities.forEach ( orderEntity -> {
//                contractOrderEntity.setId ( SnowflakeIdWorker.getInstance ().nextStringId () );
//                contractOrderEntity.setOrderId ( orderEntity.getId () );
//                contractOrderEntity.setSourceOrderType ( ConstUtil.ORDER_PROCURE_TYPE );
//                contractOrderEntity.setCreateBy ( SecurityUtils.getLoginUser ().getUser ().getUserId () );
//                contractOrderEntity.setCreateTime ( DateUtils.getNowDate () );
//                int insert = contractOrderMapper.insert ( contractOrderEntity );
//                if ( insert == 0 ) {
//                    throw new RuntimeException ( "新增采购合同与采购订单关联关系失败" );
//                }
//            } );
//        }
//        return 1;
//    }

    /**
     * 处理采购合同与采购订单的关联关系
     * 处理采购合同与物料明细关联关系
     * 先删除原有关系
     * 再新增现有关系
     * @param materialDetailEntities
     * @param contractId
     * @return
     */
    private int updateMaterial (List<MaterialDetailEntity> materialDetailEntities, String contractId) {
        if ( materialDetailEntities != null && materialDetailEntities.size () > 0 ) {
            String batchNumber = BatchNumberGenerator.generateBatchNumber ();
            //1.先删除
            contractOrderMapper.delete ( new QueryWrapper<ContractOrderEntity> ().eq ( "contract_id", contractId ).eq ( "source_contract_type", ConstUtil.CONTRACT_PROCURE_TYPE ) );
            //2.处理重复订单Id
            List<String> ids = materialDetailEntities.stream ().map ( MaterialDetailEntity :: getRelationId ).collect ( Collectors.toList () ).stream ().distinct ().collect ( Collectors.toList () );
            ids.forEach ( id -> {
                ContractOrderEntity contractOrderEntity = new ContractOrderEntity ();
                contractOrderEntity.setContractId ( contractId );
                contractOrderEntity.setSourceContractType ( ConstUtil.CONTRACT_PROCURE_TYPE );
                contractOrderEntity.setId ( SnowflakeIdWorker.getInstance ().nextStringId () );
                contractOrderEntity.setOrderId ( id );
                contractOrderEntity.setSourceOrderType ( ConstUtil.ORDER_PROCURE_TYPE );
                contractOrderEntity.setCreateBy ( SecurityUtils.getLoginUser ().getUser ().getUserId () );
                contractOrderEntity.setCreateTime ( DateUtils.getNowDate () );
                int insert = contractOrderMapper.insert ( contractOrderEntity );
                if ( insert == 0 ) {
                    throw new RuntimeException ( "新增采购合同与采购订单关联关系失败" );
                }
            } );
            materialDetailMapper.delete ( new QueryWrapper<MaterialDetailEntity> ().eq ( "relation_id", contractId ).eq ( "type", ConstUtil.CONTRACT_PROCURE_MATERIAL_TYPE ) );
            //新增现有关系
            materialDetailEntities.forEach ( materialDetailEntity -> {
                materialDetailEntity.setId ( SnowflakeIdWorker.getInstance ().nextStringId () );
                materialDetailEntity.setRelationId ( contractId );
                materialDetailEntity.setBatchNum ( batchNumber );
                materialDetailEntity.setRequireDept ( CurrentUserUtil.getCompanyId () );
                materialDetailEntity.setReceivingDept ( CurrentUserUtil.getCompanyId () );
                materialDetailEntity.setSettlementDept ( CurrentUserUtil.getCompanyId () );
                materialDetailEntity.setType ( ConstUtil.CONTRACT_PROCURE_MATERIAL_TYPE );
                materialDetailEntity.setCreateTime ( DateUtils.getNowDate () );
                int insert = materialDetailMapper.insert ( materialDetailEntity );
                if ( insert == 0 ) {
                    throw new RuntimeException ( "新增采购合同与物料明细关联关系失败" );
                }
            } );
        }
        return 1;
    }

    /**
     * 采购合同变更时，检查合同物料明细的数量是否超过采购订单里已执行完成的物料数量
     * 如果超过则不给变更成功
     * @param materialDetailEntities：新增采购合同时选择的物料
     */
    private void checkNumber (/*List<OrderEntity> orderEntities, */List<MaterialDetailEntity> materialDetailEntities) {
        //拿该采购订单的物料列表；要看目前物料列表的每条数量是不是小于已生成采购订单里物料的数量
        if ( ! CollectionUtils.isEmpty ( materialDetailEntities ) ) {
            materialDetailEntities = materialDetailEntities.stream ().filter ( detail -> StringUtils.isNotBlank ( detail.getSourceMaterialDetailId () ) ).collect ( Collectors.toList () );
            List<String> ids = materialDetailEntities.stream ().map ( MaterialDetailEntity :: getRelationId ).collect ( Collectors.toList () ).stream ().distinct ().collect ( Collectors.toList () );
            //List<String> ids = orderEntities.stream ().map ( OrderEntity :: getId ).collect ( Collectors.toList () );
            List<MaterialDetailEntity> detailEntities = materialDetailMapper.selectList ( new QueryWrapper<MaterialDetailEntity> ().eq ( "type", ConstUtil.ORDER_PURCHASE ).in ( "relation_id", ids ) );
            log.info ( "已生成采购订单的物料列表：detailEntities->{}", detailEntities );
            //1、已生成采购订单的物料，在做合同变更时不能删除，detailEntities里面的物料不能少于materialDetailEntities物料
            Set<String> materialByOrder = detailEntities.stream ().map ( MaterialDetailEntity :: getId ).collect ( Collectors.toSet () );
            Set<String> materialByContract = materialDetailEntities.stream ().map ( MaterialDetailEntity :: getId ).collect ( Collectors.toSet () );
            //检查已生成订单的物料Id是否都在新增合同的物料Id中
            boolean allExist = materialByOrder.stream ().allMatch ( materialByContract :: contains );
            if ( ! allExist ) {
                throw new RuntimeException ( "已生成采购订单的物料不能删除！" );
            }
            //2、比较detailEntities和新增的materialDetailEntities的数量，materialDetailEntities里面每一条物料数量不得小于detailEntities里每一条物料数量；
            for ( int i = 0; i < detailEntities.size (); i++ ) {
                MaterialDetailEntity materByOrder = detailEntities.get ( i );
                MaterialDetailEntity materByContract = materialDetailEntities.get ( i );
                if ( Double.parseDouble ( materByOrder.getNumber () ) > Double.parseDouble ( materByContract.getNumber () ) ) {
                    throw new RuntimeException ( "变更后的物料数量不能少于已生成采购订单的物料数量！" );
                }
            }
        }
    }

}
